import {AVALIABLE_COIN_TYPES} from './constants';
import { IBalanceRecord, ICoinTypes, IReduxBalanceInfo, IReduxMarketInfo } from '../interface';

export function utilGetAvailableByCoinType (balanceInfo: any, type: string): number {
    if (!balanceInfo) {
        return 0;
    }
    let available = balanceInfo[type] || 0;
    return available;
}

export function utilGetAddressByCoinType (balanceInfo: any, type: string) : string {
    if (!balanceInfo) {
        return '';
    }
    let address = balanceInfo[`${type}Address`];
    return address;
}

export function utilGetLockAmountByCoinType (balanceInfo: any, type: string) : number {
    if (!balanceInfo) {
        return 0;
    }
    let locked = balanceInfo[`${type}Locked`] || 0;
    return locked;
}

export function utilGetCoinInfoByCoinType (balanceInfo: any, type: string) : (Object | null) {
    if (!balanceInfo || !balanceInfo[type]) {
        return null
    }
    return balanceInfo[type];
}

export function utilCalculateAllBalance(balanceInfo: any, exchangeRate: any): number {
    const coinTypes = AVALIABLE_COIN_TYPES;
    let total = 0;
    Object.keys(coinTypes).forEach((v) => {
        let coinType = coinTypes[v];
        let rate = exchangeRate[coinType] || 0;
        total += (balanceInfo[coinType] * rate);
    })
    return total;
}

export function utilGetBalanceRecordByType(record: Array<IBalanceRecord>, type: ICoinTypes) : Array<IBalanceRecord>{
    // if (type === '')
    return record;
}

/**
 * 总资产折合BTC
 */
export function utilTotalBalanceAmountToBTC (userBalance: IReduxBalanceInfo, marketData: IReduxMarketInfo) : number {
    if (!userBalance || !marketData) {
        return 0;
    }
    let market = marketData.market;
    let total = userBalance.BTC || 0;
    for (let i = 0; i < AVALIABLE_COIN_TYPES.length; i ++) {
        // if (market.findIndex)
        let type = AVALIABLE_COIN_TYPES[i];
        let balance = userBalance[type] || 0;
        type = type + '/' + 'BTC';
        if (balance) {
            let index = market.findIndex(v => v.type === type);
            if (index >= 0) {
                let v = market[index].value;
                total += (balance * v);
            }
        }
    }
    return Number(total.toFixed(8));
}